//@Author: wulinlin
//@Description:
//@File:  UserController
//@Version: 1.0.0
//@Date: 2023/03/09 14:11

package admin

import (
	"github.com/gin-gonic/gin"
	"pingbuqingyun_django/app/models/form"
	"pingbuqingyun_django/app/models/form/userForm"
	"pingbuqingyun_django/app/services/admin"
	"pingbuqingyun_django/pkg/constant"
	"pingbuqingyun_django/pkg/tools"
)

func GetUserList(c *gin.Context) {
	queryForm := userForm.UserSearchForm{}
	res, _ := c.Get(constant.PAGINATION_KEY)
	pageInfo := res.(form.PaginateForm)
	err := c.ShouldBindQuery(&queryForm)
	if err != nil {
		tools.HandleValidatorError(c, err)
		return
	}
	data := admin.UserService.SearchUserList(queryForm, pageInfo)
	tools.JsonSuccessData(c, "获取用户列表成功", data)
}

func CreateUser(c *gin.Context) {
	uForm := userForm.CreateUserForm{}
	err := c.ShouldBindJSON(&uForm)
	if err != nil {
		tools.HandleValidatorError(c, err)
		return
	}
	uId, _ := c.Get(constant.JWT_INFO_KEY)
	data, err := admin.UserService.CreateUser(int(uId.(uint)), &uForm)
	if err != nil {
		tools.JsonErrorResp(c, err)
		return
	}
	tools.JsonSuccessData(c, "创建用户成功", data)

}

func ChangeUserPermission(c *gin.Context) {
	changeForm := userForm.ChangeUserPerForm{}
	err := c.ShouldBindJSON(&changeForm)
	if err != nil {
		tools.HandleValidatorError(c, err)
		return
	}
	err = admin.UserService.ChangePermissionService(changeForm)
	if err != nil {
		tools.JsonErrorResp(c, err)
		return
	}
	tools.JsonSuccessData(c, "修改权限成功", nil)
}

// DeactivateUser
//
//	@Description: 禁用用户接口
//	@param c
func DeactivateUser(c *gin.Context) {
	uForm := userForm.DeactivateUserForm{}
	err := c.ShouldBindJSON(&uForm)
	if err != nil {
		tools.HandleValidatorError(c, err)
		return
	}
	uId, _ := c.Get(constant.JWT_INFO_KEY)
	err = admin.UserService.DeactivateUser(uForm.Uid, int(uId.(uint)))
	if err != nil {
		tools.JsonErrorResp(c, err)
		return
	}
	tools.JsonSuccessData(c, "操作成功！", nil)
}

func ActivateUser(c *gin.Context) {
	uForm := userForm.DeactivateUserForm{}
	err := c.ShouldBindJSON(&uForm)
	if err != nil {
		tools.HandleValidatorError(c, err)
		return
	}
	uId, _ := c.Get(constant.JWT_INFO_KEY)
	err = admin.UserService.ActivateUser(uForm.Uid, int(uId.(uint)))
	if err != nil {
		tools.JsonErrorResp(c, err)
		return
	}
	tools.JsonSuccessData(c, "操作成功！", nil)
}

func ChangePwd(c *gin.Context) {
	pwdForm := userForm.ResetPwdForm{}
	err := c.ShouldBindJSON(&pwdForm)
	if err != nil {
		tools.HandleValidatorError(c, err)
		return
	}
	err = admin.UserService.ChangePwd(pwdForm)
	if err != nil {
		tools.JsonErrorResp(c, err)
		return
	}
	tools.JsonSuccessData(c, "操作成功！", nil)

}
